/**
 * 批量下载工具Logo并上传到MinIO
 * 使用方法: ts-node -r tsconfig-paths/register src/scripts/download-logos.ts
 */

import axios from 'axios';
import * as fs from 'fs';
import * as path from 'path';
import { Client } from 'minio';

// MinIO配置
const minioClient = new Client({
  endPoint: process.env.MINIO_ENDPOINT || 'localhost',
  port: parseInt(process.env.MINIO_PORT || '9100'),
  useSSL: process.env.MINIO_USE_SSL === 'true',
  accessKey: process.env.MINIO_ROOT_USER || 'minioadmin',
  secretKey: process.env.MINIO_ROOT_PASSWORD || 'minioadmin123',
});

const bucketName = process.env.MINIO_BUCKET || 'devtools-hub';

// Logo API列表（按优先级）
const logoAPIs = [
  {
    name: 'Clearbit',
    getUrl: (domain: string) => `https://logo.clearbit.com/${domain}`,
  },
  {
    name: 'Google Favicon',
    getUrl: (domain: string) => `https://www.google.com/s2/favicons?domain=${domain}&sz=256`,
  },
  {
    name: 'DuckDuckGo',
    getUrl: (domain: string) => `https://icons.duckduckgo.com/ip3/${domain}.ico`,
  },
];

/**
 * 从URL提取域名
 */
function extractDomain(url: string): string {
  try {
    return new URL(url).hostname;
  } catch {
    return '';
  }
}

/**
 * 下载Logo
 */
async function downloadLogo(url: string, apiIndex = 0): Promise<Buffer | null> {
  if (apiIndex >= logoAPIs.length) {
    console.log(`  ❌ 所有API都失败`);
    return null;
  }

  const domain = extractDomain(url);
  if (!domain) return null;

  const api = logoAPIs[apiIndex];
  const logoUrl = api.getUrl(domain);

  try {
    console.log(`  🔍 尝试 ${api.name}...`);
    const response = await axios.get(logoUrl, {
      responseType: 'arraybuffer',
      timeout: 10000,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      },
    });

    if (response.data && response.data.byteLength > 100) {
      console.log(`  ✅ 成功从 ${api.name} 获取 (${(response.data.byteLength / 1024).toFixed(2)}KB)`);
      return Buffer.from(response.data);
    }
  } catch (error: any) {
    console.log(`  ⚠️  ${api.name} 失败: ${error.message}`);
  }

  // 尝试下一个API
  return downloadLogo(url, apiIndex + 1);
}

/**
 * 上传到MinIO
 */
async function uploadToMinio(
  buffer: Buffer,
  filename: string,
): Promise<string> {
  const objectName = `tools/${filename}.png`;

  await minioClient.putObject(bucketName, objectName, buffer, buffer.length, {
    'Content-Type': 'image/png',
  });

  const publicUrl = process.env.MINIO_PUBLIC_URL || 'http://localhost:9100';
  return `${publicUrl}/${bucketName}/${objectName}`;
}

/**
 * 批量处理工具Logo
 */
async function processLogos(tools: Array<{ name: string; slug: string; url: string }>) {
  console.log(`\n🚀 开始处理 ${tools.length} 个工具Logo...\n`);

  const results = {
    success: 0,
    failed: 0,
    skipped: 0,
  };

  for (let i = 0; i < tools.length; i++) {
    const tool = tools[i];
    console.log(`\n[${i + 1}/${tools.length}] 处理: ${tool.name}`);

    try {
      // 下载Logo
      const logoBuffer = await downloadLogo(tool.url);
      
      if (!logoBuffer) {
        console.log(`  ⊘ 跳过，无法下载`);
        results.skipped++;
        continue;
      }

      // 上传到MinIO
      const uploadedUrl = await uploadToMinio(logoBuffer, tool.slug);
      console.log(`  📤 已上传: ${uploadedUrl}`);
      
      results.success++;

      // 避免请求过快
      await new Promise((resolve) => setTimeout(resolve, 500));
    } catch (error: any) {
      console.log(`  ❌ 失败: ${error.message}`);
      results.failed++;
    }
  }

  console.log('\n');
  console.log('╔══════════════════════════════════════╗');
  console.log('║   📊 处理完成                        ║');
  console.log('╚══════════════════════════════════════╝');
  console.log(`✅ 成功: ${results.success}`);
  console.log(`❌ 失败: ${results.failed}`);
  console.log(`⊘  跳过: ${results.skipped}`);
  console.log('');
}

// 示例：处理一批工具
const sampleTools = [
  { name: 'ChatGPT', slug: 'chatgpt', url: 'https://chat.openai.com' },
  { name: 'GitHub', slug: 'github', url: 'https://github.com' },
  { name: 'VSCode', slug: 'vscode', url: 'https://code.visualstudio.com' },
  // 添加更多工具...
];

// 执行
// processLogos(sampleTools);

console.log('💡 提示：');
console.log('1. 确保MinIO已启动: docker compose -f docker-compose.services.yml up -d');
console.log('2. 修改 sampleTools 数组，添加你要处理的工具');
console.log('3. 取消注释最后一行，运行: ts-node -r tsconfig-paths/register src/scripts/download-logos.ts');
console.log('');
console.log('📝 或者从数据库读取现有工具后批量处理');

